import type { ExtendedPrismaClient } from '../types/prisma-types';
import { UserRole } from '../types/prisma-types';
import { logger } from '../utils/logger';
import prisma from './prisma';

type TransactionClient = ExtendedPrismaClient;

export class SeedDataManager {
  private prisma: ExtendedPrismaClient;

  constructor() {
    this.prisma = prisma;
  }

  async seedUsers() {
    const users = [
      {
        email: 'admin@example.com',
        name: 'Admin User',
        role: UserRole.ADMIN,
        password: 'admin123'
      },
      {
        email: 'teacher@example.com',
        name: 'Teacher User',
        role: UserRole.TEACHER,
        password: 'teacher123'
      },
      {
        email: 'student@example.com',
        name: 'Student User',
        role: UserRole.STUDENT,
        password: 'student123'
      }
    ] as const;

    await this.prisma.$transaction(async (tx: TransactionClient) => {
      for (const user of users) {
        await tx.user.upsert({
          where: { email: user.email },
          update: {},
          create: user
        });
      }
    });

    logger.info('Users seeded successfully');
  }

  async clearDatabase() {
    const tables = ['User', 'Question', 'Evaluation', 'Submission', 'AuditLog'] as const;
    
    await this.prisma.$transaction(async (tx: TransactionClient) => {
      for (const table of tables) {
        await tx.$executeRaw`TRUNCATE TABLE "${table}" CASCADE`;
      }
    });

    logger.info('Database cleared successfully');
  }

  async resetAutoIncrement() {
    const tables = ['User', 'Question', 'Evaluation', 'Submission', 'AuditLog'] as const;
    
    for (const table of tables) {
      try {
        await this.prisma.$executeRaw`ALTER SEQUENCE "${table}_id_seq" RESTART WITH 1`;
      } catch (error) {
        logger.warn(`Failed to reset sequence for table ${table}`, { error });
      }
    }
  }

  async migrate() {
    try {
      await this.prisma.$executeRaw`SELECT 1`;
      logger.info('Database connection successful');
    } catch (error) {
      logger.error('Database connection failed', { error });
      throw error;
    }
  }
}

export default new SeedDataManager();
